/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle csq-3@163.com
 * @since : 2016-03-16 21:35:35
 * @filename : gulpfile.js
 * @version : 
 * @description : 
 */

//注意组件的打包方式

var gulp = require('gulp');
//var webpack = require('webpack-stream');
var webpack = require('gulp-webpack');
var clean = require('gulp-clean');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
var htmlmin = require('gulp-htmlmin');
var shell = require('gulp-shell');
var copyext = require('gulp-copy-ext');
var webpackConfig = require("./webpack.config.js");
var minimist = require('minimist');
var options = minimist(process.argv.slice(2));


//参考：https://github.com/shama/webpack-stream 
//如果path报错，兼容写法为path:require("path").resolve("./dist/")，既可以单独webpack又可以glup调用
gulp.task('webpack', function () {
    return gulp.src('')//从webpack配置里获取
    .pipe(webpack(require('./webpack.config.prod.js')))
    //.pipe(rename({suffix: '.min'}))
    //.pipe(uglify())// 只能压缩JS，所以这有CSS输入会报错。
    .pipe(gulp.dest('./dist/static/'));
});

gulp.task('copy', function() {
   gulp.src('./favicon.ico')
        .pipe(copyext({}))
        .pipe(gulp.dest('./dist/'));
});

gulp.task('cssmin', function() {
    return gulp.src('dist/static/css/*.css')
    //.pipe(rename({suffix: '.min'}))
    .pipe(minifyCss())
    .pipe(gulp.dest('./dist/static/css/')); 
});

gulp.task('jsmin', function () {
   return gulp.src('dist/static/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('dist/static/'));
});

gulp.task('imagemin', function () {
    return gulp.src('./src/resource/img/*.{jpeg,png,jpg}')
    .pipe(imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [pngquant()]
    }))
    .pipe(gulp.dest('./dist/static/img/'));
});

gulp.task('htmlmin', function() {
  return gulp.src('./src/index.html')
    .pipe(htmlmin({
        removeComments : true,
        collapseWhitespace: true,
        minifyJS: true,
        minifyCSS: true
    }))
    .pipe(gulp.dest('./dist'));
});

gulp.task('distclean', function() {  
    return gulp.src('./dist/*', {read: false})
    .pipe(clean());
});

gulp.task('version', shell.task([
    'echo version:'+options.version,
    'sed -i "" "s/?v=[0-9.]*/?v='+options.version+'/g" ./src/index.html'
    //'sed -i "s/?v=[0-9.]*/?v='+options.version+'/g" ./src/*.html'
]));

//gulp --key1 value1 --key2 value2
gulp.task('default',['distclean'],function() {
    gulp.run('webpack','htmlmin','imagemin','copy');
});

//gulp --key1 value1 --key2 value2
gulp.task('webpackjs',function() {
    gulp.run('webpack');
});

//gulp dev --version 2.0.0   2.0传递进去会变为2
gulp.task('prod',['distclean'],function() {
    if (options.version) {
        gulp.run('webpack','imagemin','htmlmin','version');
    } else {
        console.log('version is null');
    }
});






